let currentQueryParams = {}; // ← 新增：保存当前查询参数
let currentTableData = []; // ← 新增：保存当前表格数据
layui.use(['element', 'table', 'form', 'layer', 'laydate', 'laytpl'], function () {
    const $ = layui.$,
        element = layui.element,
        table = layui.table,
        form = layui.form,
        layer = layui.layer,
        laydate = layui.laydate;
    // 初始化门岗数据映射
    let gateMap = {};

    // 加载门岗数据
    async function loadGates() {
        try {
            const res = await $.ajax({
                url: window.appConfig.apiBaseUrl +'/gate/all',
                method: 'GET'
            });

            if (res.code === 0 && Array.isArray(res.data)) {
                res.data.forEach(item => {
                    gateMap[item.id] = item.gateName;
                });
                return res.data;
            } else {
                throw new Error('门岗数据格式错误');
            }
        } catch (error) {
            console.error('门岗数据加载失败:', error);
            layer.msg('门岗数据加载失败', {icon: 2});
            return [];
        }
    }

    // 添加全局单位映射
    let unitMap = {};

    async function loadUnits() {
        try {
            const res = await $.ajax({
                url: window.appConfig.apiBaseUrl +'/unit/all',
                method: 'GET'
            });

            if (res && Array.isArray(res.data)) {
                // 清空旧数据
                unitMap = {};
                // 填充 unitMap
                res.data.forEach(item => {
                    unitMap[item.id] = item.unitName;
                });
                console.log('unitMap 已更新:', unitMap);
                return res.data;
            } else {
                throw new Error('单位数据格式错误');
            }
        } catch (error) {
            console.error('加载单位失败:', error);
            layer.msg('单位数据加载失败', {icon: 2});
            return [];
        }
    }


    // 材料管理表格
    const materialTable = table.render({
        elem: '#materialTable',
        url: window.appConfig.apiBaseUrl +'/material/list',
        cols: [[{
            field: 'id',
            title: 'ID',
            width: 80
        }, {
            field: 'materialName',
            title: '材料类型',
            width: 150
        }, {
            field: 'density',
            title: '密度',
            width: 120,
            templet: d => (d.density || 0).toFixed(2)
        }, {
            title: '操作',
            width: 200,
            toolbar: '#infoActionTpl'
        }]],
        page: true,
        limit: 10,
        response: {statusCode: 0},
        request: {
            pageName: 'pageNum',
            limitName: 'pageSize'
        },
        done: function (res) {
            if (!res || !Array.isArray(res.data)) {
                layer.msg('数据格式异常', {icon: 2});
            }
        }
    });

    // 车辆尺寸管理表格
    const truckSizeTable = table.render({
        elem: '#truckSizeTable',
        url: window.appConfig.apiBaseUrl +'/truck-type/list',
        cols: [[{
            field: 'id',
            title: 'ID',
            width: 80
        }, {
            field: 'truckTypeName',
            title: '车辆类型',
            width: 150
        }, {
            field: 'height',
            title: '高度',
            width: 120,
            templet: d => (d.height || 0).toFixed(2)
        }, {
            field: 'width',
            title: '宽度',
            width: 120,
            templet: d => (d.width || 0).toFixed(2)
        }, {
            field: 'length',
            title: '长度',
            width: 120,
            templet: d => (d.length || 0).toFixed(2)
        }, {
            title: '操作',
            width: 200,
            toolbar: '#infoActionTpl'
        }]],
        page: true,
        limit: 10,
        response: {statusCode: 0},
        request: {
            pageName: 'pageNum',
            limitName: 'pageSize'
        },
        done: function (res) {
            if (!res || !Array.isArray(res.data)) {
                layer.msg('数据格式异常', {icon: 2});
            }
        }
    });

    // 车辆信息管理表格
    const truckUnitTable = table.render({
        elem: '#truckUnitTable',
        url: window.appConfig.apiBaseUrl +'/truck-unit/list',
        cols: [[{
            field: 'id',
            title: 'ID',
            width: 80
        }, {
            field: 'plate',
            title: '车牌号',
            width: 150
        }, {
            field: 'truckTypeName',
            title: '车辆类型',
            width: 150
        }, {
            field: 'unitName',
            title: '所属单位',
            width: 180
        }, {
            title: '操作',
            width: 200,
            toolbar: '#infoActionTpl'
        }]],
        page: true,
        limit: 10,
        response: {statusCode: 0},
        request: {
            pageName: 'pageNum',
            limitName: 'pageSize'
        },
        done: function (res) {
            if (!res || !Array.isArray(res.data)) {
                layer.msg('数据格式异常', {icon: 2});
            }
        }
    });

    // 单位管理表格
    const unitTable = table.render({
        elem: '#unitTable',
        url: window.appConfig.apiBaseUrl +'/unit/list',
        cols: [[{
            field: 'id',
            title: 'ID',
            width: 80
        }, {
            field: 'unitName',
            title: '单位名称',
            width: 200
        }, {
            title: '操作',
            width: 200,
            toolbar: '#infoActionTpl'
        }]],
        page: true,
        limit: 10,
        response: {
            statusCode: 0
        },
        request: {
            pageName: 'page',
            limitName: 'size'
        },
        done: function (res) {
            if (!res || !Array.isArray(res.data)) {
                layer.msg('数据格式异常', {icon: 2});
            }
        }
    });

    // 门岗管理表格
    const gateTable = table.render({
        elem: '#gateTable',
        url: window.appConfig.apiBaseUrl +'/gate/list',
        cols: [[{
            field: 'id',
            title: 'ID',
            width: 80
        }, {
            field: 'gateName',
            title: '门岗名称',
            width: 200
        }, {
            title: '操作',
            width: 200,
            toolbar: '#infoActionTpl'
        }]],
        page: true,
        limit: 10,
        response: {statusCode: 0},
        request: {
            pageName: 'pageNum',
            limitName: 'pageSize'
        },
        done: function (res) {
            if (!res || !Array.isArray(res.data)) {
                layer.msg('数据格式异常', {icon: 2});
            }
        }
    });

    // 更新当前时间
    function updateCurrentTime() {
        const now = moment().format('YYYY年MM月DD日 HH:mm:ss');
        $('#currentTime').text(now);
        $('#currentTimeMobile').text(now);
    }

    setInterval(updateCurrentTime, 1000);
    updateCurrentTime(); // 初始化一次
    // 初始化日期选择器
    laydate.render({elem: '#startTime', type: 'datetime'});
    laydate.render({elem: '#endTime', type: 'datetime'});

    // 用户管理表格
    const userTable = table.render({
        elem: '#userTable',
        url: window.appConfig.apiBaseUrl +'/user/list',
        cols: [[
            {field: 'id', title: 'ID', width: 80},
            {field: 'username', title: '用户名', width: 150},
            {
                field: 'password',
                title: '密码',
                width: 120,
                templet: () => '******' // 显示为密文
            },
            {
                field: 'isAdmin', title: '角色', width: 120, templet: d => d.isAdmin ?
                    '<span class="layui-badge layui-bg-blue">管理员</span>' :
                    '<span class="layui-badge layui-bg-gray">普通用户</span>'
            },
            {field: 'unitId', title: '所属单位', width: 180, templet: d => unitMap[d.unitId] || '未知单位'},
            {
                field: 'registerTime',
                title: '注册时间',
                width: 160,
                templet: d => moment(d.registerTime).format('YYYY-MM-DD HH:mm:ss')
            },
            {title: '操作', width: 200, toolbar: '#userActionTpl'}
        ]],
        page: true,
        limit: 10,
        response: {
            statusCode: 0
        },
        request: {
            pageName: 'pageNum',   // 默认就是 page
            limitName: 'pageSize'   // 如果后端接收的是 size，必须显式声明
        },
        done: function () {
            // 表格加载完成后的回调
        }
    });

    // 数据查询表格
    const dataTable = table.render({
        elem: '#dataTable',
        url: window.appConfig.apiBaseUrl +'/truck-record/list',
        request: {
            pageName: 'pageNum',   // 对应后端接收的页码参数名
            limitName: 'pageSize'   // 对应后端接收的每页条数参数名
        },
        cols: [[
            {field: 'id', title: '序号', width: 60},
            {field: 'uuid', title: '唯一标识', width: 60},
            {field: 'gateName', title: '门岗', width: 80},
            {field: 'unitName', title: '施工单位', width: 90},
            {field: 'plate', title: '车牌号', width: 90},
            {field: 'time', title: '时间', width: 80},
            {field: 'materialName', title: '材料', width: 60},
            {field: 'density', title: '密度', width: 60, templet: d => (d.density || 0).toFixed(2)},
            {field: 'volume', title: '体积(m³)', width: 80, templet: d => (d.volume || 0).toFixed(2)},
            {field: 'weight', title: '重量(吨)', width: 80, templet: d => (d.weight || 0).toFixed(2)},
            {
                field: 'scanStatus', title: '扫描状态', width: 60, templet: d => d.scanStatus ?
                    '<span class="layui-badge layui-bg-green">已扫描</span>' :
                    '<span class="layui-badge layui-bg-orange">未扫描</span>'
            },
            {
                field: 'syncStatus', title: '同步状态', width: 60, templet: d => d.syncStatus ?
                    '<span class="layui-badge layui-bg-green">已同步</span>' :
                    '<span class="layui-badge layui-bg-orange">未同步</span>'
            },
            {title: '操作', width: 180, toolbar: '#userActionTpl'}
        ]],
        page: true,
        limit: 10,
        limits: [10, 20, 50, 100, 200, 500, 1000],
        response: {
            statusCode: 200,     // 成功的状态码
            countName: 'count', // 后端返回的总记录数字段
            dataName: 'data'    // 后端返回的数据字段
        },
        done: function (res) {
            // 增加数据格式验证
            if (res.data && Array.isArray(res.data)) {
                updateStatistics(res);
                currentTableData = res.data;
            } else {
                layer.msg('数据格式异常', {icon: 2});
            }
        }
    });

    // 更新统计信息
    function updateStatistics(data) {
        const totalWeight = data.totalWeight || 0;
        const totalVolume = data.totalVolume || 0;
        const totalCount = data.count || 0;

        $('#totalWeight').text(totalWeight.toFixed(2));
        $('#totalVolume').text(totalVolume.toFixed(2));
        $('#totalCount').text(totalCount);
    }
    async function populateGateSelect(gates) {
        const gateSelect = $('#gateName');
        gateSelect.empty().append('<option value="">请选择</option>'); // 清空并添加默认项
        gates.forEach(gate => {
            gateSelect.append(`<option value="${gate.gateName}">${gate.gateName}</option>`);
        });
        form.render('select'); // 刷新layui表单元素
    }

    function populateUnitSelect(units) {
        const unitSelect = $('#unitName');
        unitSelect.empty().append('<option value="">请选择</option>');
        units.forEach(unit => {
            unitSelect.append(`<option value="${unit.unitName}">${unit.unitName}</option>`);
        });
        form.render('select'); // 刷新layui表单元素
    }


    $(document).on('change', 'input[type="checkbox"][data-target]', function () {
        const target = $('#' + $(this).data('target'));
        const isChecked = this.checked;

        if (isChecked) {
            target.removeAttr('disabled');
        } else {
            target.attr('disabled', 'disabled').val('').trigger('change');
        }
    });


    // 页面加载完成后执行
    $(document).ready(async function () {
        // await initUnits();  // 先加载单位数据
        // 先加载所有需要的数据
        const [units, gates] = await Promise.all([
            loadUnits(),
            loadGates()
        ]);
        populateGateSelect(gates);
        populateUnitSelect(units);
        const username = sessionStorage.getItem('username');
        const unitId = sessionStorage.getItem('unitId');

        if (!username || !unitId) {
            layer.msg('请先登录', {icon: 2});
            setTimeout(() => window.location.href = '/login.html', 1500);
        } else {
            $('#usernameDisplay').text(username);
            $('#usernameDisplayMobile').text(username);

            element.init();

            // 根据 URL hash 切换到指定标签页
            const hash = location.hash.replace('#', '');
            if (hash) {
                const $navItem = $(`.layui-nav-item[data-tab="${hash}"]`);
                if ($navItem.length > 0) {
                    $navItem.addClass('layui-this').siblings().removeClass('layui-this');
                    element.tabChange('adminTabs', hash);
                }
            }
        }
    });

    // 导航栏切换事件
    $(document).on('click', '.layui-nav-item', function () {
        const $navItem = $(this);
        const tabId = $navItem.data('tab');
        if (!tabId) return;

        // 更新导航状态
        $navItem.addClass('layui-this').siblings().removeClass('layui-this');

        // 切换标签页
        setTimeout(() => {
            element.render('nav');
            element.tabChange('adminTabs', tabId);
        }, 100);
    });

    // 监听窗口变化重新渲染
    $(window).on('resize', function () {
        element.render('tab');
        element.render('nav');
    });

    // 在用户输入时实时检查用户名
    $('#usernameInput').on('blur', function () {
        if (!this.value) return;

        $.get(window.appConfig.apiBaseUrl +'/user/check?username=' + this.value, function (res) {
            if (res.exists) {
                layer.tips('用户名已存在', '#usernameInput', {tips: 1});
            }
        }).fail(function (xhr) {
            console.error('检查用户名失败:', xhr);
        });
    });

    function deleteUser(data) {
        layer.confirm('确定删除该用户？', {
            icon: 3,
            title: '确认删除'
        }, function (index) {
            $.ajax({
                url: `${window.appConfig.apiBaseUrl}/user/${data.id}`,
                type: 'DELETE',
                success: () => {
                    layer.msg('删除成功', {icon: 1});
                    userTable.reload();
                },
                error: xhr => {
                    console.error('删除用户失败:', xhr);
                    layer.msg('删除失败: ' + (xhr.responseJSON?.message || xhr.statusText), {icon: 2});
                }
            });
            layer.close(index);
        });
    }

// 用户管理操作
    table.on('tool(userTable)', function (obj) {
        const data = obj.data;
        if (obj.event === 'edit') {
            editUser(data);
        } else if (obj.event === 'delete') {
            deleteUser(data);
        }
    });

    function deleteTruckRecord(data) {
        layer.confirm('确定删除该记录？', {
            icon: 3,
            title: '确认删除'
        }, function (index) {
            $.ajax({
                url: `${window.appConfig.apiBaseUrl}/truck-record/${data.id}`,
                type: 'DELETE',
                success: () => {
                    layer.msg('删除成功', {icon: 1});
                    dataTable.reload(); // 刷新表格
                },
                error: xhr => {
                    console.error('删除记录失败:', xhr);
                    layer.msg('删除失败: ' + (xhr.responseJSON?.message || xhr.statusText), {icon: 2});
                }
            });
            layer.close(index);
        });
    }

// 数据编辑操作
    table.on('tool(dataTable)', function (obj) {
        const data = obj.data;

        if (obj.event === 'edit') {
            window.location.href = `admin_truck_record.html?mode=edit&id=${data.id}`;
        } else if (obj.event === 'delete') {
            deleteTruckRecord(data);
        }
    });
    // 添加数据功能
    $('#addDataBtn').click(() => {
        window.location.href = 'admin_truck_record.html?mode=add';
    });

    // 添加用户功能
    $('#addUserBtn').click(() => {
        window.location.href = 'admin_user.html?mode=add';
    });

    // 点击「编辑用户」跳转到 admin_user.html 并带参数
    function editUser(data) {
        const params = new URLSearchParams({
            mode: 'edit',
            id: data.id,
            username: data.username,
            isAdmin: data.isAdmin,
            unitId: data.unitId
        });
        window.location.href = `admin_user.html?${params.toString()}`;
    }


    // 数据编辑表单提交
    form.on('submit(dataEditForm)', function (data) {
        const fields = data.field;



        if (!fields.plate) {
            layer.msg('车牌号不能为空', {icon: 2});
            return false;
        }

        if (!fields.time) {
            layer.msg('时间不能为空', {icon: 2});
            return false;
        }

        // 转换数值类型
        fields.density = parseFloat(fields.density) || 0;
        fields.volume = parseFloat(fields.volume) || 0;
        fields.weight = parseFloat(fields.weight) || 0;

        console.log('提交编辑数据:', fields);

        $.ajax({
            url: window.appConfig.apiBaseUrl +'/truck-record/update',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(fields),
            success: () => {
                layer.msg('更新成功');
                dataTable.reload();
                layer.closeAll();
            },
            error: xhr => {
                console.error('更新数据失败:', xhr);
                const errorMsg = xhr.responseJSON?.message || '更新失败';
                layer.msg(errorMsg, {icon: 2});
            }
        });

        return false;
    });

    // 更新 currentQueryParams，只保留勾选并填写的字段
    function updateCurrentQueryParams(formData) {
        const newParams = {};

        // 门岗参数处理
        if (formData.useGateName === 'on' && formData.gateName) {
            newParams.gateName = formData.gateName;
        }

        // 车牌号参数处理
        if (formData.usePlate === 'on' && formData.plate) {
            newParams.plate = formData.plate;
        }

        // 施工单位参数处理
        if (formData.useUnitName === 'on' && formData.unitName && formData.unitName !== '请选择') {
            newParams.unitName = formData.unitName;
        }

        // 开始时间参数处理
        if (formData.useStartTime === 'on' && formData.startTime) {
            newParams.startTime = formData.startTime;
        }

        // 结束时间参数处理
        if (formData.useEndTime === 'on' && formData.endTime) {
            newParams.endTime = formData.endTime;
        }

        // 更新全局参数
        currentQueryParams = newParams;
    }



    // 查询表单提交
    form.on('submit(queryForm)', function (data) {
        const formData = data.field;

        updateCurrentQueryParams(formData);

        console.log('查询参数:', currentQueryParams);


        // 重载表格，传入查询参数
        dataTable.reload({
            where: {...currentQueryParams},
            page: {curr: 1}, // 重新从第 1 页开始
            url: window.appConfig.apiBaseUrl +'/truck-record/list?_=' + new Date().getTime()  // 添加时间戳防止缓存
        });

        return false;
    });





    $('#exportBtn').click(function () {
        const loadingIndex = layer.load(1);

        try {
            // 获取并格式化查询参数
            const params = new URLSearchParams(currentQueryParams);
            formatQueryDates(params);

            // 构建下载链接
            const timestamp = moment().format('YYYYMMDDHHmmss');
            const filename = `车辆数据_${timestamp}.xlsx`;
            const url = `/truck-record/export?${params.toString()}`;

            // 创建隐藏的 <a> 标签进行下载
            const link = document.createElement('a');
            link.href = url;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            layer.msg('导出成功', {icon: 1});
        } catch (error) {
            console.error('导出失败:', error);
            layer.msg('导出失败: ' + (error.message || '服务器错误'), {icon: 2});
        } finally {
            layer.close(loadingIndex);
        }
    });

    /* 以下为辅助函数 */
    function formatQueryDates(params) {
        ['startTime', 'endTime'].forEach(key => {
            if (params.has(key)) {
                const dateStr = params.get(key);
                const formatted = moment(dateStr).format('YYYY-MM-DD HH:mm:ss');
                params.set(key, formatted);
            }
        });
    }

    // 材料管理操作
    table.on('tool(materialTable)', function (obj) {
        const data = obj.data;
        if (obj.event === 'edit') {
            editMaterial(data);
        } else if (obj.event === 'delete') {
            deleteMaterial(data);
        }
    });

    // 车辆尺寸管理操作
    table.on('tool(truckSizeTable)', function (obj) {
        const data = obj.data;
        if (obj.event === 'edit') {
            editTruckType(data);
        } else if (obj.event === 'delete') {
            deleteTruckType(data);
        }
    });

    // 车辆信息管理操作
    table.on('tool(truckUnitTable)', function (obj) {
        const data = obj.data;
        if (obj.event === 'edit') {
            editTruckUnit(data);
        } else if (obj.event === 'delete') {
            deleteTruckUnit(data);
        }
    });

    // 单位管理操作
    table.on('tool(unitTable)', function (obj) {
        const data = obj.data;
        if (obj.event === 'edit') {
            editUnit(data);
        } else if (obj.event === 'delete') {
            deleteUnit(data);
        }
    });

    // 门岗管理操作
    table.on('tool(gateTable)', function (obj) {
        const data = obj.data;
        if (obj.event === 'edit') {
            editGate(data);
        } else if (obj.event === 'delete') {
            deleteGate(data);
        }
    });

    // 添加材料
    $('#addMaterialBtn').click(() => {
        window.location.href = 'admin_material.html?mode=add';
    });

    // 编辑材料
    function editMaterial(data) {
        const params = new URLSearchParams({
            mode: 'edit',
            id: data.id,
            materialName: data.materialName,
            density: data.density
        });
        window.location.href = `admin_material.html?${params.toString()}`;
    }


    // 删除材料
    function deleteMaterial(data) {
        layer.confirm('确定删除该材料？', {
            icon: 3,
            title: '确认删除'
        }, function (index) {
            $.ajax({
                url: `${window.appConfig.apiBaseUrl}/material/${data.id}`,
                type: 'DELETE',
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg('删除成功', {icon: 1});
                        materialTable.reload();
                    } else {
                        layer.msg('删除失败', {icon: 2});
                    }
                },
                error: function (xhr) {
                    console.error('删除材料失败:', xhr);
                    layer.msg(`删除失败: ${xhr.statusText}`, {icon: 2});
                }
            });
            layer.close(index);
        });
    }


    // 添加车辆类型
    $('#addTruckSizeBtn').click(() => {
        window.location.href = 'admin_truck_type.html?mode=add';
    });

    // 编辑车辆类型
    function editTruckType(data) {
        const params = new URLSearchParams({
            mode: 'edit',
            id: data.id,
            truckTypeName: data.truckTypeName,
            height: data.height,
            width: data.width,
            length: data.length
        });
        window.location.href = `admin_truck_type.html?${params.toString()}`;
    }

    // 删除车辆尺寸
    function deleteTruckType(data) {
        layer.confirm('确定删除该车辆类型？', {
            icon: 3,
            title: '确认删除'
        }, function (index) {
            $.ajax({
                url: `${window.appConfig.apiBaseUrl}/truck-type/${data.id}`,
                type: 'DELETE',
                success: function (res) {
                    if (res) {
                        layer.msg('删除成功', {icon: 1});
                        truckSizeTable.reload();
                    } else {
                        layer.msg('删除失败', {icon: 2});
                    }
                },
                error: function (xhr) {
                    console.error('删除失败:', xhr);
                    layer.msg(`删除失败: ${xhr.statusText}`, {icon: 2});
                }
            });
            layer.close(index);
        });
    }

    // 添加车辆信息
    $('#addTruckUnitBtn').click(() => {
        window.location.href = 'admin_truck_unit.html?mode=add';
    });

    // 编辑车辆信息
    function editTruckUnit(data) {
        const params = new URLSearchParams({
            mode: 'edit',
            id: data.id,
            plate: data.plate,
            truckType: data.truckTypeName,
            unitName: data.unitName
        });
        window.location.href = `admin_truck_unit.html?${params.toString()}`;
    }


    // 删除车辆信息
    function deleteTruckUnit(data) {
        layer.confirm('确定删除该车辆信息？', {
            icon: 3,
            title: '确认删除'
        }, function (index) {
            $.ajax({
                url: `${window.appConfig.apiBaseUrl}/truck-unit/${data.id}`,
                type: 'DELETE',
                success: function (res) {
                    if (res) {
                        layer.msg('删除成功', {icon: 1});
                        truckUnitTable.reload();
                    } else {
                        layer.msg('删除失败', {icon: 2});
                    }
                },
                error: function (xhr) {
                    console.error('删除失败:', xhr);
                    layer.msg(`删除失败: ${xhr.statusText}`, {icon: 2});
                }
            });
            layer.close(index);
        });
    }

    // 添加单位
    $('#addUnitBtn').click(() => {
        window.location.href = 'admin_unit.html?mode=add';
    });

    // 编辑单位
    function editUnit(data) {
        const params = new URLSearchParams({
            mode: 'edit',
            id: data.id,
            unitName: data.unitName
        });
        window.location.href = `admin_unit.html?${params.toString()}`;
    }

    // 删除单位
    function deleteUnit(data) {
        layer.confirm('确定删除该单位？', {
            icon: 3,
            title: '确认删除'
        }, function (index) {
            $.ajax({
                url: `${window.appConfig.apiBaseUrl}/unit/${data.id}`,
                type: 'DELETE',
                success: function (res) {
                    if (res.code === 0) {
                        layer.msg('删除成功', {icon: 1});
                        unitTable.reload();
                    } else {
                        layer.msg('删除失败', {icon: 2});
                    }
                },
                error: function (xhr) {
                    console.error('删除失败:', xhr);
                    layer.msg(`删除失败: ${xhr.statusText}`, {icon: 2});
                }
            });
            layer.close(index);
        });
    }

    // 添加门岗
    $('#addGateBtn').click(() => {
        window.location.href = 'admin_gate.html?mode=add';
    });

    // 编辑门岗
    function editGate(data) {
        const params = new URLSearchParams({
            mode: 'edit',
            id: data.id,
            gateName: data.gateName
        });
        window.location.href = `admin_gate.html?${params.toString()}`;
    }

    // 删除门岗
    function deleteGate(data) {
        layer.confirm('确定删除该门岗？', {
            icon: 3,
            title: '确认删除'
        }, function (index) {
            $.ajax({
                url: `${window.appConfig.apiBaseUrl}/gate/${data.id}`,
                type: 'DELETE',
                success: function (res) {
                    if (res.code === 0) {
                        layer.msg('删除成功', {icon: 1});
                        gateTable.reload();
                    } else {
                        layer.msg('删除失败', {icon: 2});
                    }
                },
                error: function (xhr) {
                    console.error('删除失败:', xhr);
                    layer.msg(`删除失败: ${xhr.statusText}`, {icon: 2});
                }
            });
            layer.close(index);
        });
    }

    // 登出功能
    $('#logoutBtn').click(function () {
        layer.confirm('确定要退出系统吗？', {
            icon: 3,
            title: '确认退出'
        }, function (index) {
            // 清除会话信息
            sessionStorage.removeItem('username');
            sessionStorage.removeItem('unitId');

            // 跳转到登录页面
            window.location.href = '/login.html';
            layer.close(index);
        });
    });

    // 自定义表单验证
    form.verify({
        username: function (value, item) {
            // 跳过被禁用的字段验证
            if (item.disabled) return;

            if (value.length < 2) {
                return '用户名至少需要2个字符';
            }
            if (/[^\w\u4e00-\u9fa5]/.test(value)) {
                return '用户名只能包含字母、数字、下划线和中文';
            }
        },
        password: function (value) {
            if (value.length < 6) {
                return '密码至少需要6个字符';
            }
            if (!/[A-Za-z]/.test(value) || !/[0-9]/.test(value)) {
                return '密码需要同时包含字母和数字';
            }
        },
        materialName: function (value) {
            if (!value) {
                return '材料类型不能为空';
            }
            if (value.length < 2) {
                return '材料类型至少需要2个字符';
            }
        },
        unitName: function (value) {
            if (!value) {
                return '单位名称不能为空';
            }
            if (value.length < 2) {
                return '单位名称至少需要2个字符';
            }
        },
        plate: function (value) {
            if (value && !/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}[A-HJ-NP-Z]{1}[A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]{0,1}$/.test(value)) {
                return '请输入正确的车牌号格式';
            }
        }
    });

    // 重置表单
    window.resetForm = function () {
        form.val('dataEditForm', {
            gate: '',
            unitName: '',
            plate: '',
            time: '',
            materialName: '',
            density: '',
            volume: '',
            weight: ''
        });
    };
});








